import os
import uuid
from fastapi import UploadFile
import aiofiles
from app.core.config import settings
import qiniu  # 需要安装七牛云SDK: pip install qiniu

class FileService:
    UPLOAD_DIR = "uploads"  # 本地临时存储
    IMAGE_DIR = os.path.join(UPLOAD_DIR, "images")
    FILE_DIR = os.path.join(UPLOAD_DIR, "files")

    @classmethod
    async def ensure_directories(cls):
        for directory in [cls.IMAGE_DIR, cls.FILE_DIR]:
            if not os.path.exists(directory):
                os.makedirs(directory)
                
    @classmethod
    async def upload_to_qiniu(cls, file_path: str, file_name: str) -> str:
        """上传文件到七牛云存储"""
        # 初始化七牛云客户端
        q = qiniu.Auth(settings.QINIU_AK, settings.QINIU_SK)
        # 生成上传Token
        token = q.upload_token(settings.QINIU_BUCKET, file_name)
        
        # 上传文件
        ret, info = qiniu.put_file(token, file_name, file_path)
        if ret and ret['key'] == file_name:
            # 上传成功，返回文件URL
            return f"https://{settings.QINIU_DOMAIN}/{file_name}"
        else:
            # 上传失败，返回本地文件路径（可以根据需要修改）
            return f"/static/{os.path.basename(os.path.dirname(file_path))}/{os.path.basename(file_path)}"

    @classmethod
    async def upload_image(cls, file: UploadFile, user_id: int) -> str:
        await cls.ensure_directories()
        ext = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{ext}"
        file_path = os.path.join(cls.IMAGE_DIR, unique_filename)
        
        # 保存到本地临时文件
        async with aiofiles.open(file_path, 'wb') as out_file:
            content = await file.read()
            await out_file.write(content)
            
        # 上传到七牛云
        qiniu_key = f"images/{unique_filename}"
        return await cls.upload_to_qiniu(file_path, qiniu_key)

    @classmethod
    async def upload_file(cls, file: UploadFile, user_id: int) -> str:
        await cls.ensure_directories()
        ext = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{ext}"
        file_path = os.path.join(cls.FILE_DIR, unique_filename)
        
        # 保存到本地临时文件
        async with aiofiles.open(file_path, 'wb') as out_file:
            content = await file.read()
            await out_file.write(content)
            
        # 上传到七牛云
        qiniu_key = f"files/{unique_filename}"
        return await cls.upload_to_qiniu(file_path, qiniu_key) 